/*H-ui.admin.js v2.3.1 date:15:42 2015.08.19 by:guojunhui*/
/*获取顶部选项卡总长度*/
function tabNavallwidth(){
	var taballwidth=0,
		$tabNav = $(".acrossTab"),
		$tabNavWp = $(".Hui-tabNav-wp"),
		$tabNavitem = $(".acrossTab li"),
		$tabNavmore =$(".Hui-tabNav-more");
	if (!$tabNav[0]){return}
	$tabNavitem.each(function(index, element) {
        taballwidth+=Number(parseFloat($(this).width()+60))});
	$tabNav.width(taballwidth+25);
	var w = $tabNavWp.width();
	if(taballwidth+25>w){
		$tabNavmore.show()}
	else{
		$tabNavmore.hide();
		$tabNav.css({left:0})}
}

/*左侧菜单响应式*/
function Huiasidedisplay(){
	if($(window).width()>=768){
		$(".Hui-aside").show()
	} 
}
function getskincookie(){
	var v = getCookie("Huiskin");
	if(v==null||v==""){
		v="default";
	}
	$("#skin").attr("href","skin/"+v+"/skin.css");
}
$(function(){
	getskincookie();
	//layer.config({extend: 'extend/layer.ext.js'});
	Huiasidedisplay();
	var resizeID;
	$(window).resize(function(){
		clearTimeout(resizeID);
		resizeID = setTimeout(function(){
			Huiasidedisplay();
		},500);
	});
	
	$(".Hui-nav-toggle").click(function(){
		$(".Hui-aside").slideToggle();
	});
	$(".Hui-aside").on("click",".menu_dropdown dd li a",function(){
		if($(window).width()<768){
			$(".Hui-aside").slideToggle();
		}
	});
	/*左侧菜单*/
	$.Huifold(".menu_dropdown dl dt",".menu_dropdown dl dd","fast",1,"click");
	/*选项卡导航*/
	
	$(".Hui-aside").on("click",".menu_dropdown a",function(){
		if($(this).attr('_href')){
			var bStop=false;
			var bStopIndex=0;
			var _href=$(this).attr('_href');
			var _titleName=$(this).html();
			var topWindow=$(window.parent.document);
			var show_navLi=topWindow.find("#min_title_list li");
			show_navLi.each(function() {
				if($(this).find('span').attr("data-href")==_href){
					bStop=true;
					bStopIndex=show_navLi.index($(this));
					return false;
				}
			});
			if(!bStop){
				creatIframe(_href,_titleName);
				min_titleList();
			}
			else{
				show_navLi.removeClass("active").eq(bStopIndex).addClass("active");
				var iframe_box=topWindow.find("#iframe_box");
				iframe_box.find(".show_iframe").hide().eq(bStopIndex).show().find("iframe").attr("src",_href);
			}
		}
	});
	
	function min_titleList(){
		var topWindow=$(window.parent.document);
		var show_nav=topWindow.find("#min_title_list");
		var aLi=show_nav.find("li");
	};
	function creatIframe(href,titleName){
		var topWindow=$(window.parent.document);
		var show_nav=topWindow.find('#min_title_list');
		show_nav.find('li').removeClass("active");
		var iframe_box=topWindow.find('#iframe_box');
		show_nav.append('<li class="active"><span data-href="'+href+'">'+titleName+'</span><i></i><em></em></li>');
		tabNavallwidth();
		var iframeBox=iframe_box.find('.show_iframe');
		iframeBox.hide();
		iframe_box.append('<div class="show_iframe"><div class="loading"></div><iframe frameborder="0" src='+href+'></iframe></div>');
		var showBox=iframe_box.find('.show_iframe:visible');
		showBox.find('iframe').attr("src",href).load(function(){
			showBox.find('.loading').hide();
		});
	}

	var num=0;
	var oUl=$("#min_title_list");
	var hide_nav=$("#Hui-tabNav");
	$(document).on("click","#min_title_list li",function(){
		var bStopIndex=$(this).index();
		var iframe_box=$("#iframe_box");
		$("#min_title_list li").removeClass("active").eq(bStopIndex).addClass("active");
		iframe_box.find(".show_iframe").hide().eq(bStopIndex).show();
	});
	$(document).on("click","#min_title_list li i",function(){
		var aCloseIndex=$(this).parents("li").index();
		$(this).parent().remove();
		$('#iframe_box').find('.show_iframe').eq(aCloseIndex).remove();	
		num==0?num=0:num--;
		tabNavallwidth();
	});
	$(document).on("dblclick","#min_title_list li",function(){
		var aCloseIndex=$(this).index();
		var iframe_box=$("#iframe_box");
		if(aCloseIndex>0){
			$(this).remove();
			$('#iframe_box').find('.show_iframe').eq(aCloseIndex).remove();	
			num==0?num=0:num--;
			$("#min_title_list li").removeClass("active").eq(aCloseIndex-1).addClass("active");
			iframe_box.find(".show_iframe").hide().eq(aCloseIndex-1).show();
			tabNavallwidth();
		}else{
			return false;
		}
	});
	tabNavallwidth();
	
	$('#js-tabNav-next').click(function(){
		num==oUl.find('li').length-1?num=oUl.find('li').length-1:num++;
		toNavPos();
	});
	$('#js-tabNav-prev').click(function(){
		num==0?num=0:num--;
		toNavPos();
	});
	
	function toNavPos(){
		oUl.stop().animate({'left':-num*100},100);
	}
	
	/*换肤*/
	$("#Hui-skin .dropDown-menu a").click(function(){
		var v = $(this).attr("data-val");
		setCookie("Huiskin", v);
		$("#skin").attr("href","skin/"+v+"/skin.css");
	});
}); 
/*弹出层*/
/*
	参数解释：
	title	标题
	url		请求的url
	id		需要操作的数据id
	w		弹出层宽度（缺省调默认值）
	h		弹出层高度（缺省调默认值）
*/
function layer_show(title,url,w,h){
	if (title == null || title == '') {
		title=false;
	};
	if (url == null || url == '') {
		url="404.html";
	};
	if (w == null || w == '') {
		w=800;
	};
	if (h == null || h == '') {
		h=($(window).height() - 50);
	};
	layer.open({
		type: 2,
		area: [w+'px', h +'px'],
		fix: false, //不固定
		maxmin: true,
		shade:0.4,
		title: title,
		content: url
	});
}
/*关闭弹出框口*/
function layer_close(){
	var index = parent.layer.getFrameIndex(window.name);
	parent.layer.close(index);
};

/*上传控件*/
/*注：upload.setFileTypes('*.txt;*.doc;*.xls', '文档类型'); 的调用必须在Upload_File初始化之后，并且不能紧挨着初始化代码，要另写方法设置*/
function Upload_File(id, type, size, img, multiple, panel) {
    var swfs;
    this.swfu = swfs;
    var file_types = "*.jpg;*.gif;*.png;*.jpeg;*.bmp";
    var file_size = 25;
    var file_img = "/admin/images/adduploads.gif";
    var file_multiple = SWFUpload.BUTTON_ACTION.SELECT_FILE;
    var allsize = 0;
    var hasload = 0;
    if (type) {
        file_types = type;
    }
    if (size) {
        file_size = size;
    }
    if (img) {
        file_img = img;
    }
    if (multiple) {
        file_multiple = SWFUpload.BUTTON_ACTION.SELECT_FILES;
    }
    var swfuOption = {//swfupload选项
        upload_url: "/admin/tools/Upload.ashx", //接收上传的服务端url
        flash_url: "/admin/js/swfupload.swf", //swfupload压缩包解压后swfupload.swf的url
        button_placeholder_id: id, //上传按钮占位符的id
        file_size_limit: "20MB", //用户可以选择的文件大小，有效的单位有B、KB、MB、GB，若无单位默认为KB
        file_upload_limit: 0,  // 上传文件的总个数
        file_queue_limit: 0,   // 每次能上传的文件个数
        file_types: file_types,
        custom_settings: {
            progressTarget: "fsUploadProgress",
            cancelButtonId: "btnCancel"
        },
        post_params: {
            "ASPSESSID": "<%=Session.SessionID %>"
        },
        multiple: true,
        button_width: file_size, //按钮宽度
        button_height: file_size, //按钮高度
        button_action: file_multiple,
        //button_action: SWFUpload.BUTTON_ACTION.SELECT_FILE,  //单选
        //button_action: SWFUpload.BUTTON_ACTION.SELECT_FILES, //多选
        button_image_url: file_img,
        button_text_style: '.btn-txt{color: #666666;font-size:20px;font-family:"微软雅黑"}',
        button_cursor: SWFUpload.CURSOR.HAND,
        upload_success_handler: uploadSuccess, //文件上传成功
        upload_complete_handler: uploadComplete,
        file_queued_handler: fileQueued,
        upload_progress_handler: uploadProgress,
        file_queue_error_handler: fileQueueError,
        file_dialog_complete_handler: fileDialog,
        file_dialog_start_handler: prevDialog,
        file_dialog_complete_handler: afterDialog,
        debug: false
    };

    function uploadSuccess(file, serverData) {
        var json = $.parseJSON(serverData);
        if (json.length > 0) {
            if (this.handle == "upload_product") {
                $("#upload_products").addClass("hidden");
                $("#upload_show").removeClass("hidden");
                $("#img_container").html("<img src='" + json[0] + "'/>");
            } else if (this.handle == "upload_annex") {
                $(".upload_product").addClass("hidden");
                $(".upload_show").removeClass("hidden");
                $(".img_container div").attr("class", Get_Icon(json[0]));
                $(".img_container").attr("val", json[0]);
            } else if (this.handle == "upload_img") {
                var info = json[0];
                var dian = info.lastIndexOf(".");
                $("#" + file.id).attr("src", info.substring(0, dian) + "_50" + info.substring(dian, info.length)).attr("val", info).css("margin-top", "0px").parent().css("border", "1px solid #fff");
            }
            else if (this.handle == "upload_file") {
                $("#img_container2").append('<div class="img"><img src="'+json[0]+'"/><span onclick="remove_img(this)"></span></div>');
            } else if (this.handle == "upload_file2") {

            }
        }
    };
    function afterDialog() {
        var option = {};
        var date = new Date();
        option.handle = this.handle;
        option.random = date.Format("hhmmss");
        if (this.handle == "upload_file2") {
            option.id = productid;
        }
        swfs.setPostParams(option);
        if (file_types == "*.jpg;*.gif;*.png;*.jpeg;*.bmp") {
            swfs.startUpload();
        }
    };
    function uploadComplete(file) {
        if (swfs.getStats().files_queued > 0) {  //没有这句，则只上传第一个文件
            swfs.startUpload();
        } else {
            if (this.handle == "upload_file2") {
                Init_Img(productid);
            }
        }
    };
    function fileQueued(file) {
        if (this.handle == "upload_product") {
        }
        else if (this.handle == "upload_img") {
            Init_Img(panel, file);
        } 
    };
    function uploadProgress(file, bytesLoaded) {
        
    };
    function fileQueueError(file, errorCode, message) {
        try {
            switch (errorCode) {
                case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                    alert("文件大小为0");
                    break;
                case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                    alert("您选择的文件大小为【" + GetSize(file.size) + "】，单个文件大小不能超过【" + swfs.settings.file_size_limit + "】");
                    break;
                case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
                    break;
                default:
                    alert(message);
                    break;
            }

        } catch (ex) {
            this.debug(ex);
        }
    };
    function fileDialog() {
    };
    function prevDialog() {
    };
    function InitSize() {
        var list = $("#" + panel + " .list .size");
        if (list.length > 0) {
            $("#" + panel).parent().removeClass("hidden");
        } else {
            $("#" + panel).parent().addClass("hidden");
        }
        var allsize = 0;
        $.each(list, function (i, info) {
            allsize += parseInt($(info).attr("val"));
        });
        $("#" + panel).next().html("共" + list.length + "个文件，总大小" + GetSize(allsize) + "，<a href='javascript:void(0)' onclick='" + panel.substring(0, panel.length - 1) + ".RemoveAll()' >全部取消</a>");
    };
    this.RemoveFile = function (o) {
        $(o).parent().parent().remove();
        var id = $(o).attr("val");
        InitSize();
        swfs.cancelUpload(id, false);
    };
    this.RemoveAll = function () {
        $("#" + panel).html("");
        var list = $("#" + panel + " .list .img img");
        $("#" + panel).parent().addClass("hidden");
        $.each(list, function (i, info) {
            swfs.cancelUpload($(info).attr("id"), false);
        });

    };
    swfs = new SWFUpload(swfuOption);
    this.swfu = swfs;
};

function Init_Img(pid) {

    var data = {};
    data.act = "Find_AnnexByPID";
    data.pid = pid;
    Ajax.Post("/admin/tools/Admin.ashx", data, function (r) {
        var json = $.parseJSON(r);
        if (json.state) {
            var str = "";
            $.each(json.data, function (i, info) {
                str += '<div class="img"><img src="' + info.path + '"/><span onclick="remove_img2(this,'+info.id+')"></span></div>';
            });
            $("#img_container2").html(str);
        }
    });
};

Date.prototype.Format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //month 
        "d+": this.getDate(), //day 
        "h+": this.getHours(), //hour 
        "m+": this.getMinutes(), //minute 
        "s+": this.getSeconds(), //second 
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter 
        "S": this.getMilliseconds() //millisecond 
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};


//重新上传产品图片
function Re_Upload() {
    $("#upload_products").removeClass("hidden");
    $("#upload_show").addClass("hidden");
    $("#img_container img").attr("src", "");
};


var Ajax = {
    Get: function (url, func) {
        return $.get(encodeURI(url), func);
    },
    Post: function (url, data, func) {
        return $.post(url, data, func);
    }
};


var Pager = {
    Init: function (pageindex, pagesize, recordcount, fun, id) {

        //记录数
        //每页显示条数
        //当前页
        var str = "";
        var k = 0;
        if (pageindex == 0) {
            pageindex = 1;
        }
        var page = parseInt((recordcount - 1) / pagesize + 1);  //总页数

        if (recordcount > 0) {
            str += "<div class='divPG'><a val='1' ><div id='pgf' class='divPG1' onmouseover='changebg2(this)' onmouseout='changebg1(this)'>首页</div></a><a val='" + (pageindex - 1) + "' ><div id='pgp' class='divPG1'  onmouseover='changebg2(this)' onmouseout='changebg1(this)'>上页</div></a>";
        }
        if (pageindex < 7) {
            k = 7 - pageindex;
        }
        else if (page - pageindex < 7) {
            k = page - 6 - pageindex;
        }
        else {
            k = 0;
        }

        for (var i = 1; i <= page; i++) //不足之处，有多少页就循环多少页，有待改进
        {
            if (i < 3 || i > (page - 2) || i >= (pageindex + k - 4) && i <= (pageindex + k + 4)) //4为左右2测的页码数1234  5  6789
            {
                str += "<a val='" + i + "' ><div id='pg" + i + "' class='divPG1' onmouseover='changebg2(this)' onmouseout='changebg1(this)'>" + i + "</div></a>";
            }
            if (page > 14 && (i == page - 3 && page - pageindex > 6 || i == 3 && pageindex > 7)) {
                str += "<div class='divPG2'>...</div>";
            }
        }
        if (recordcount > 0) {
            str += "<a val='" + (pageindex + 1) + "'><div id='pgn' class='divPG1' onmouseover='changebg2(this)' onmouseout='changebg1(this)'>下页</div></a><a val='" + page + "'><div id='pgl' class='divPG1' onmouseover='changebg2(this)' onmouseout='changebg1(this)'>尾页</div></a></div>";
        }
        var page_id = "pager";
        if (id == "2") {
            $("#pagers").html(str);
            page_id = "pagers";
        } else {
            $("#pager").html(str);
            page_id = "pager";
        }
        if (recordcount > 0) {
            if (pageindex == 1) {
                var pgf = $("#" + page_id + " #pgf");
                pgf.css("border", "1px solid #d5d2d2");
                pgf.css("color", "#d5d2d2");
                pgf.attr("onmouseover", "");
                pgf.attr("onmouseout", "");
                pgf.parent().attr("onclick", "");

                var pgp = $("#" + page_id + " #pgp");
                pgp.css("border", "1px solid #d5d2d2");
                pgp.css("color", "#d5d2d2");
                pgp.attr("onmouseover", "");
                pgp.attr("onmouseout", "");
                pgp.parent().attr("onclick", "");

            }
            if (pageindex == page) {
                var pgn = $("#" + page_id + " #pgn");
                pgn.css("border", "1px solid #d5d2d2");
                pgn.css("color", "#d5d2d2");
                pgn.attr("onmouseover", "");
                pgn.attr("onmouseout", "");
                pgn.parent().attr("onclick", "");

                var pgl = $("#" + page_id + " #pgl");
                pgl.css("border", "1px solid #d5d2d2");
                pgl.css("color", "#d5d2d2");
                pgl.attr("onmouseover", "");
                pgl.attr("onmouseout", "");
                pgl.parent().attr("onclick", "");
            }
            if (pageindex <= page) {
                var pgi = $("#" + page_id + " #pg" + pageindex);
                pgi.css("border", "1px solid #454444");
                pgi.css("background", "#eeeded");
                pgi.css("color", "#454444");
                pgi.css("fontWeight", "bold");
                pgi.attr("onmouseover", "");
                pgi.attr("onmouseout", "");
                pgi.addClass("select");
                pgi.parent().attr("href", "javascript:void(0)");
            }
            else {
                $("#" + page_id + " #pg" + page).parent().click();
            }
        }
        $("#pager a").click(function () {
            fun(parseInt($(this).attr("val")));
        });
    }
};
function changebg2(o) {
    o.style.border = "1px solid #838282";
    o.style.background = "#eeeded";
};
function changebg1(o) {
    o.style.border = "1px solid #929292";
    o.style.background = "white";
};